import CustomerSellerApi from '#/api/work/userInfo'
import { ref } from 'vue'
import { message } from 'ant-design-vue'
const PageApi = CustomerSellerApi.inst
const videoFun = () => {
    const video = document.querySelector('video')
        if (video) {
            video
                .play()
                .then(() => {
                    console.log(`autoplay well`)
                })
                .catch((e) => {
                    console.log(`autoplay fail, wait for first click`)
                    if (e instanceof DOMException) {
                        // play before user intersact
                        const autoPlayAfterAnyClick = () => {
                            video.play()
                            document.removeEventListener('click', autoPlayAfterAnyClick)
                        }

                        document.addEventListener('click', autoPlayAfterAnyClick)
                        throw e
                    } else {
                        // or rethrow
                        throw e
                    }
                })
        }
}
export async function setIntervalMsg() {
    
    /**
     * 获取聊天消息列表
     */
    // 定时器
    const timer = ref<any>(null)
    const res = await PageApi.getSessionList({})
    localStorage.setItem('sessionList', JSON.stringify(res))
    // 轮询
    const isGet = ref<boolean>(false)
    timer.value = setInterval(async () => {
        if (isGet.value) {
            return false
        }
        isGet.value = true
        const res = await PageApi.getSessionList({})
        if (res) {
            isGet.value = false
            const sessionListStr = localStorage.getItem('sessionList')
            const localMsg = sessionListStr ? JSON.parse(sessionListStr) : {}
            if (res.length > 0 && localMsg && localMsg.length > 0) {
                const date1 = new Date(res[0].createTime).getTime()
                const date2 = new Date(localMsg[0].createTime).getTime()
                if (date1 > date2) {
                    message.success(`您有新消息`)
                    videoFun()
                }
            }
            localStorage.setItem('sessionList', JSON.stringify(res))
        } else {
            message.error(`获取聊天消息列表失败!`)
        }
    }, 5000)
}
